import { Injectable } from '@nestjs/common';
import { CreateTypeManageDto } from './dto/create-type-manage.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { resultUtil } from 'src/utils/result';
import * as dayjs from 'dayjs';

@Injectable()
export class TypeManageService {
  constructor(private readonly prismaService: PrismaService) {}

  // 新增分类名称
  async create(createTypeManageDto: CreateTypeManageDto) {
    const res = await this.prismaService.typeManage.findFirst({
      where: {
        title: createTypeManageDto.title,
      },
    });
    if (res) {
      return resultUtil('分类存在', '000001');
    }
    await this.prismaService.typeManage.create({
      data: {
        ...createTypeManageDto
      }
    })
    return resultUtil('', '000000');
  }
  // 获取分类列表
  async queryType(queryInfo) {
    const { title, currentPage, pageSize } = queryInfo;
    const skip = (currentPage - 1) * pageSize;

    const where = {} as any;
    if (title) {
      where.title = { contains: title };
    }
    const [records, total] = await Promise.all([
      this.prismaService.typeManage.findMany({
        where,
        skip,
        take: pageSize,
        orderBy: {
          id: 'desc',
        },
      }),
      this.prismaService.typeManage.count({ where }),
    ]);
    return resultUtil('', '000000', {
      records: records?.map((item: any) => {
        let result = {
          ...item,
          createdAt: dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
        }
        return result
      }),
      total: total,
    });
  }
  /**
   * 获取所有分类
  */
  async getAll() {
    const result = await this.prismaService.typeManage.findMany({
      select: {
        id: true,
        title: true
      }
    })
    return resultUtil('', '000000', result ?? [])
  }
    /**
   * 删除分类
   */
    async delete(id: number) {
      await this.prismaService.typeManage.delete({
        where: { id: +id },
      });
      return resultUtil('', '000000');
    }
}
